﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using cmdLineParserModule;

namespace cmdLineParserModule
{
    /// <summary>
    /// Option class for marking bool attribute, usable with 'int' or 'int?' only
    ///</summary>
    public class optionIntAttribute : optionParametrizedAttribute
    {
        /// <summary>
        /// Minimum value that can be entered by user
        /// </summary>
        public int min = int.MinValue;

        /// <summary>
        /// Maximum value that can be entered by user
        /// </summary>
        public int max = int.MaxValue;

        /// <summary>
        /// Expected type of property marked with this class
        /// </summary>
        /// <returns></returns>
        internal override Type typeAccepted()
        {
            if (choiceRequired)
                return typeof(int);
            else
                return typeof(int?);
        }

        /// <summary>
        /// Checks class settings validity
        /// </summary>
        protected override void customCheck()
        {
            base.customCheck();
            checkDefaultValue();
        }

        /// <summary>
        /// Checks defaultValue definition (if defined, must be in <min, max>)
        /// </summary>
        private void checkDefaultValue()
        {
            if (defaultValue == null)
                return;

            if ((int)defaultValue < min || (int)defaultValue > max)
                throw new WrongDefinitionException("defaultValue {0} is out of range ({1} to {2})  (property {3}).", defaultValue, min, max, fieldFullName());
        }

        /// <summary>
        /// Creates integer value from string
        /// </summary>
        /// <param name="stringValue">String containing integer value</param>
        /// <returns>Integer value from string</returns>
        internal override object createValueFromString(string stringValue)
        {
            int value;
            if (!int.TryParse(stringValue, out value))
                throw new WrongUsageException("Cannot convert {0} to integer value.", stringValue);

            if (value < min || value > max)
                throw new WrongUsageException("{0} is out of range ({1} to {2}).", value, min, max);

            return value;
        }
    }
}
